package cn.tedu.fileupload;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.util.unit.DataSize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.MultipartConfigElement;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;


/**
 * @author shkstart
 * @create 2020-07-25 11:34
 */
@RestController
public class FileUploadController {

    @Value("${project.upload-location}")
    private String parent;

    @PostMapping("/upload")
    public String upload(MultipartFile image, HttpServletRequest request) throws IOException {
        String parent = request.getServletContext().getRealPath("20200725");
        System.out.println("parent ="+parent);
        File parentFile = new File(parent);
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }

        //关于文件名的策略:时间+随机数
        String filename = UUID.randomUUID().toString();
        //处理扩展名
        //获取原始文件名
        String originalFilename= image.getOriginalFilename();
        //暂定扩展名为空字符串
        String suffix = "";
        //如果源文件名中存在有效的扩展名,则截取
        int beginIndex = originalFilename.lastIndexOf(".");
        if (beginIndex > 0){
            suffix = originalFilename.substring(beginIndex);
        }
        //得到完整的文件名
        String child = filename + suffix;
        image.transferTo(new File(parent,child));
        return child;
    }


}
